package online.mjchow.fic.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * Created by mjchow
 * Date       2017/6/23
 * Time       9:35
 */
public class JWTUtil {

    private static SecretKey secretKey = null;
    static {
        String stringKey = "^sT4jAJnxXwE1)-+(eOI2qW8qijI4&*";
        byte[] encodeKey = Base64.getEncoder().encode(stringKey.getBytes());
        secretKey = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
    }

    public static String createJWT(String id, int type, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Claims claims = new DefaultClaims();
        claims.put("type", type);
        claims.put("id", id);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .setClaims(claims)
                .signWith(signatureAlgorithm, secretKey);
        if(ttlMillis>0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    public static Claims parseJWT(String jwt) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {

        }
        return claims;
    }

//    public static void main(String[] args) throws Exception {
//        String jwtStr = createJWT("11", 0, 1000000000);
//        System.out.println(jwtStr);
//    }
}
